package com.weixin.paleituo.view;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ScrollView;

/**
 * 扩展ScrollView，监听滑动事件
 * 通过滑动监听{@link OnMonitorScrollListener}进行事件监听
 *
 * @author fengzhen
 * @version v1.0, 2018/4/1
 */
public class MonitorScrollView extends ScrollView {

    private OnMonitorScrollListener monitorScrollListener;

    public MonitorScrollView(Context context) {
        super(context);
    }

    public MonitorScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MonitorScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setMonitorScrollListener(OnMonitorScrollListener monitorScrollListener) {
        this.monitorScrollListener = monitorScrollListener;
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        // 向下滑动8 判定为向下滑
        if (oldt < t && (oldt - t) < 8) {
            if (monitorScrollListener != null) {
                monitorScrollListener.scrollDown();
            }
        }

        // 距离顶部小于5，滑动到顶部
        if (t < 5) {
            if (monitorScrollListener != null) {
                monitorScrollListener.scrollViewTop();
            }
        }
    }

    /**
     * 为{@link MonitorScrollView}设置滑动监听事件，处理所需要的情况
     * {@link #scrollDown()} :向下滑动事件处理
     * {@link #scrollViewTop()}：滑动到顶部事件处理
     *
     * @author fengzhen
     * @version v1.0, 2018/4/1
     */
    public interface OnMonitorScrollListener {

        /**
         * 当{@link MonitorScrollView}滑动到最顶部，触发此事件
         */
        void scrollViewTop();

        /**
         * 当{@link MonitorScrollView}向下滑，触发此事件
         */
        void scrollDown();
    }
}
